package com.fh.utils.intercept;



import com.fh.utils.RedisUtils;
import com.fh.utils.annotation.NeedToken;
import com.fh.utils.annotation.PassToken;
import com.utils.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author whf
 * @date 2023年04月25日 15:10
 */
@Component
@Slf4j
public class LoginIntercept implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }
        Method method = handlerMethod.getMethod();

        if(method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        if(!method.isAnnotationPresent(NeedToken.class)) {
            throw new BusinessException("没有注解不通过");
        }
        NeedToken needToken = method.getAnnotation(NeedToken.class);
        if(!needToken.token()) {
            return true;
        }

        String token = request.getHeader("Token");
        if(!StringUtils.hasText(token)) {
            log.error("没有Token不予通过");
            throw new BusinessException("没有Token");
        }
        String tokenId = request.getHeader("TokenID");
        if(!StringUtils.hasText(tokenId)) {
            throw new BusinessException("没有TokenID不予通过");
        }
        String judgment = redisUtils.getToken(tokenId);
        if(!StringUtils.hasText(judgment)){
            throw new BusinessException("Token已经过期");
        }
        if(judgment.equals(token)) {
            return true;
        }
        throw new BusinessException("没有Token不予通过");
    }
}
